import axios from "axios"
import { ElMessage, ElMessageBox } from "element-plus"
import { errorMessages } from "vue/compiler-sfc"

const service = axios.create({
    baseURL: 'http://127.0.0.1:8000/api',
    timeout: 5000
})

service.interceptors.request.use(
    config => {
        config.headers = config.headers || {}
        if (localStorage.getItem('token')) {
            config.headers.Authorization = localStorage.getItem('token')||''
        }
        return config
    },
    error => {
        console.log(error);
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        if (response.status !== 200 && response.status !== 201) {
            ElMessage({
                message: response.data.message || 'Error',
                type: 'error',
                duration: 5 * 1000
            })
        }

        if (response.status === 404 || response.status ===50012 || response.status === 50014) {
                ElMessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
                    confirmButtonText: 'Re-Login',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(() => {
                    localStorage.dispatch('usr/logout').then(() => {
                        location.reload();
                    });
                });
            }
        else {
            return response.data
        }
    },
    error => {
        console.log('err' + error)
        ElMessage({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service